<template>
     <div class="rightBoxContainer">
          <div class="titleBox">
               <span v-if="chartData?.province">
                    {{ chartData?.province + ' ' + chartData?.city + ' ' + chartData?.conty + ' ' + chartData?.village }}
               </span>
               <span v-else>请选择行政区划</span>
          </div>
          <div class="searchBox">
               <page-search
                    pageName="pages_container"
                    v-if="searchFormConfigRef"
                    ref="pageSearchRef"
                    :searchConfig="searchFormConfigRef"
                    @queryBtnClick="handleQueryClick"
                    @resetBtnClick="handleResetClick"
                    @searchChange="searchChange">
                    <template #button></template>
               </page-search>
          </div>
          <div class="tableBox">
               <page-content
                    v-if="contentTableConfigRef"
                    ref="pageContentRef"
                    :tableLoading="tableLoading"
                    pageName="pages_container"
                    :contentConfig="contentTableConfigRef"
                    @getTableList="getTableList"
                    @editBtnClick="handleEditData"
                    @delBtnClick="handleDelData"
                    @getSelectionData="getSelectionData"
                    :deleteBtnShow="false"
                    :editBtnShow="false"
                    :showHandle="false">
                    <template #btns></template>
                    <template #createtime="scoped">
                         {{ scoped.row.createtime ? formatDate(scoped.row.createtime) : '-' }}
                    </template>
                    <template #starttime="scoped">
                         {{ scoped.row.starttime ? formatDate(scoped.row.starttime) : '-' }}
                    </template>
                    <template #endtime="scoped">
                         {{ scoped.row.endtime ? formatDate(scoped.row.endtime) : '-' }}
                    </template>
                    <template #updatetime="scoped">
                         {{ scoped.row.updatetime ? formatDate(scoped.row.updatetime) : '-' }}
                    </template>
                    <template #meetingRecord="scoped">
                         <el-button type="primary" size="small" title="事件记录" @click="meetRecordBtn(scoped.row)">
                              <i class="iconfont icon-shijianjilu"></i>
                         </el-button>
                    </template>
               </page-content>
          </div>
          <page-modal
               v-if="modalConfigRef"
               ref="pageModalRef"
               :modalConfig="modalConfigRef"
               :defaultInfo="modalInfo"
               pageName="pages_container"
               @addSuccess="addSuccess"
               @editSuccess="editSuccess"></page-modal>
          <el-dialog v-model="meetRecordDialog" title="事件记录" width="80%" destroy-on-close>
               <div class="meetRecordContainer">
                    <div class="leftBox">
                         <mapBox
                              ref="mapBoxRef"
                              :startTime="activeSupvisionData?.starttime"
                              :endTime="activeSupvisionData?.endtime"
                              :meetRecord="meetRecord"></mapBox>
                    </div>
                    <div class="rightBox">
                         <div v-if="meetRecord && meetRecord.length">
                              <div class="meetRecordBox" v-for="item in meetRecord" :key="item.id">
                                   <div class="dleteBtn" @click="deleteThing(item)" title="删除">
                                        <i class="iconfont icon-shanchu"></i>
                                   </div>
                                   <div class="positionBtn" @click="positionThing(item)" title="定位">
                                        <i class="iconfont icon-dingwei"></i>
                                   </div>
                                   <div class="boxTitle">
                                        {{ item.createtime }}
                                   </div>
                                   <div class="boxContent">
                                        <div class="boxLeft">
                                             <el-image
                                                  style="width: 100%; height: 120px"
                                                  :src="item.activePath"
                                                  :zoom-rate="1.2"
                                                  :max-scale="7"
                                                  :min-scale="0.2"
                                                  :preview-src-list="item.paths"
                                                  :initial-indexpx="4"
                                                  fit="cover" />
                                        </div>
                                        <div class="boxRight">
                                             <div class="boxRightRow">
                                                  地方段长 :
                                                  <span>
                                                       {{ item.dfduanzahng }}
                                                  </span>
                                             </div>
                                             <div class="boxRightRow">
                                                  地方总段长 :
                                                  <span>
                                                       {{ item.dfallduanzhang }}
                                                  </span>
                                             </div>
                                             <div class="boxRightRow">
                                                  其他人 :
                                                  <span>
                                                       {{ item.other }}
                                                  </span>
                                             </div>
                                             <div class="boxRightRow">
                                                  事件描述 :
                                                  <span>
                                                       {{ item.describe }}
                                                  </span>
                                             </div>
                                             <div class="boxRightRow">
                                                  位置信息 :
                                                  <span>
                                                       {{ item.address }}
                                                  </span>
                                             </div>
                                        </div>
                                   </div>
                              </div>
                         </div>
                         <el-empty v-else description="暂无数据" />
                    </div>
               </div>
               <template #footer>
                    <div class="dialog-footer">
                         <el-button @click="meetRecordDialog = false">取消</el-button>
                    </div>
               </template>
          </el-dialog>
     </div>
</template>

<script setup lang="ts">
import pageContent from '@/components/pageContent'
import pageSearch from '@/components/pageSearch'
import pageModal from '@/components/pageModal'
import { usePageTable } from '@/hooks/table/usePageTable'
import { contentTableConfig } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'
import { GetDuDaoPc, SelectThing, DeleteThing } from '@/api/supervisionRecords'
import useUserStore from '@/store/modules/user'
import { formatDate, parseMileage } from '@/utils/formtFun'
import { ElMessage, ElMessageBox } from 'element-plus'
import mapBox from '../mapBox/index.vue'
let userStore = useUserStore()
let props = defineProps({
     chartData: {
          type: Object as PropType<any>,
     },
})

// 单个删除方法回调
const delHandleCallback = async (val: any) => {
     try {
          // let obj = {
          //      ids: val ?? modalInfo.value.id,
          // }
          // const { code } = await DeleteMeet(obj)
          // const message = code == 200 ? '删除成功' : '删除失败'
          // ElMessage({ type: code == 200 ? 'success' : 'error', message })
          // pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const {
     searchFormConfigRef,
     contentTableConfigRef,
     modalConfigRef,
     pageModalRef,
     pageContentRef,
     pageSearchRef,
     modalInfo,
     tableLoading,
     selectCheckData,
     permissionRef,
     handleOnSuccess,
     handleNewData,
     handleEditData,
     handleDelData,
     handleQueryClick,
     handleResetClick,
     getSelectionData,
     templateDownloadClick,
     hasPermission,
} = usePageTable(null, null, null, delHandleCallback)
onMounted(async () => {
     await getSelectOptions()
     contentTableConfigRef.value = contentTableConfig
     searchFormConfigRef.value = searchFormConfig
     modalConfigRef.value = modalConfig
     nextTick(() => {
          pageSearchRef.value?.handleResetClick()
     })
})
const searchChange = (data: any) => {
     console.log('searchChange', data)
}

const getTableList = async (params: any) => {
     console.log(params, 99999)
     try {
          const requestParams = {
               ...params,
               ...props.chartData,
               starttime: params.starttime ? params.starttime + ' 00:00:00' : '',
               endtime: params.endtime ? params.endtime + ' 23:59:59' : '',
          }
          tableLoading.value = true
          const tabelData: any = await GetDuDaoPc(requestParams)
          tableLoading.value = false
          const newData = tabelData.Data || []
          const newTotal = Number(tabelData.Count) || 0
          nextTick(() => {
               if (newData.length > 0) {
                    pageContentRef.value!.setTableData(newData, newTotal)
               } else {
                    pageContentRef.value!.setTableData([], 0)
               }
          })
     } catch (error) {
          tableLoading.value = false
          console.error('Failed to get table data:', error)
     }
}

// 新增的回调方法
const addSuccess = async (val: any) => {
     try {
          // let obj = {
          //      ...val,
          // }
          // const res = await AddMeet(obj)
          // const message = res == '新增成功' ? '添加成功' : '添加失败'
          // ElMessage({ type: res == 200 ? 'success' : 'error', message })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}

// 编辑的回调方法
const editSuccess = async (val: any) => {
     try {
          // let obj = {
          //      ...val,
          // }
          // const res = await UpdateMeet(obj)
          // const message = res == '修改成功' ? '编辑成功' : '编辑失败'
          // ElMessage({ type: res == '修改成功' ? 'success' : 'error', message })
          // pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
// 获取对应选择器的下拉选项
const getSelectOptions = async () => {
     try {
     } catch (error) {
          console.error(error)
     }
}
watch(
     () => props.chartData,
     () => {
          pageSearchRef.value?.handleQueryClick()
     },
     { deep: true },
)
const activeSupvisionId = ref('')
const meetRecord: any = ref([])
const meetRecordDialog = ref(false)
const activeSupvisionData: any = ref({})
const meetRecordBtn = async (val: any) => {
     activeSupvisionId.value = val.supervisionid
     activeSupvisionData.value = val
     await getMettingRecord(val.supervisionid)
     meetRecordDialog.value = true
}
const urlFun = (url: any) => {
     // 获取当前环境变量
     const env = import.meta.env.VITE_SERVE
     // console.log('url', url ? env + url?.split('~')[1] : '')
     return url ? env + url?.split('~')[1] : ''
}
const getMettingRecord = async (val: any = undefined) => {
     try {
          meetRecord.value = []
          let obj = {
               surpervisionId: val ?? activeSupvisionId.value,
               description: '',
          }

          const res: any = await SelectThing(obj)
          if (res && res.length) {
               meetRecord.value = res.map((item: any) => {
                    return {
                         ...item,
                         createtime: formatDate(item.createtime, 'yyyy-mm-dd hh:mm'),
                         paths:
                              item.pictures &&
                              JSON.parse(item.pictures).map((item: any) => {
                                   return urlFun(item.path)
                              }),
                         activePath: item.pictures && JSON.parse(item.pictures)[0] && urlFun(JSON.parse(item.pictures)[0].path),
                         pathTotal: item.pictures && JSON.parse(item.pictures).length,
                    }
               })
          }
     } catch (error) {
          console.log(error)
     }
}
// 删除事件记录
const deleteThing = async (val: any) => {
     try {
          ElMessageBox.confirm('是否确认删除当前事件记录?', '警告', {
               confirmButtonText: '确认',
               cancelButtonText: '取消',
               type: 'warning',
          })
               .then(async () => {
                    let obj = {
                         thingid: val.thingid,
                    }
                    console.log('obj', obj)
                    const res: any = await DeleteThing(obj)
                    if (res == '删除事件及关联图片成功！') {
                         ElMessage({
                              type: 'success',
                              message: '删除成功',
                         })
                         getMettingRecord()
                    } else {
                         ElMessage({
                              type: 'error',
                              message: '删除失败',
                         })
                    }
               })
               .catch(() => {
                    console.log('取消删除')
               })
     } catch (error) {
          console.log(error)
     }
}
const mapBoxRef: any = ref(null)
// 定位到事件
const positionThing = async (val: any) => {
     mapBoxRef.value && mapBoxRef.value.flytoGemotry(val.geom)
}
</script>

<style lang="scss" scoped>
.rightBoxContainer {
     width: 100%;
     height: 100%;
     display: flex;
     flex-direction: column;
     overflow: auto;
     padding-right: 5px;

     .titleBox {
          width: 100%;
          height: 5%;
          color: #fff;
          font-weight: bold;
          font-size: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #0a3e6e;
          border-radius: 5px;
     }

     .searchBox {
          width: 100%;
          height: auto;
     }

     .tableBox {
          height: 80%;
          width: 100%;
          border-radius: 10px;
     }
}

.meetRecordContainer {
     position: relative;
     height: 58vh;
     width: 100%;
     display: flex;
     justify-content: space-between;
     box-sizing: border-box;

     .leftBox {
          width: 58%;
          height: 100%;
     }

     .rightBox {
          width: 40%;
          height: 100%;
          overflow-y: auto;

          .meetRecordBox {
               width: 98%;
               height: 180px;
               padding: 10px;
               border: 1px solid #188fc6;
               display: flex;
               min-height: 120px;
               flex-direction: column;
               margin-bottom: 15px;
               border-radius: 10px;
               position: relative;

               .dleteBtn,
               .positionBtn {
                    position: absolute;
                    right: 10px;
                    top: 10px;
                    z-index: 999;
                    padding: 7px;
                    border-radius: 50%;
                    background-color: #0d506f;
                    color: #fff;
                    cursor: pointer;

                    &:hover {
                         background-color: #188fc6;
                    }
               }

               .positionBtn {
                    right: 50px;
               }

               &:hover {
                    box-shadow: 0 0 5px #188fc6;
               }

               .boxTitle {
                    width: 100%;
                    height: 40px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 15px;
                    color: #0276ce;
                    font-weight: bold;
                    font-size: 16px;
               }

               .boxContent {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    justify-content: space-between;

                    .boxLeft {
                         display: flex;
                         align-items: center;
                         justify-content: center;
                         width: 25%;
                         height: 100%;
                         border-right: 1px solid #9b9898b6;
                         padding-right: 10px;
                         margin-right: 10px;
                    }

                    .boxRight {
                         width: 75%;
                         display: flex;
                         flex-direction: column;
                         overflow: auto;

                         .boxRightRow {
                              width: 100%;
                              color: #fff;
                              height: auto;
                              font-weight: bold;
                              line-height: 20px;

                              span {
                                   color: #ccc;
                                   font-weight: none;
                                   margin: 5px;
                              }
                         }
                    }
               }
          }
     }
}
</style>
